
package com.shop.cloud.mall.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.mall.common.entity.UserBalance;
import com.shop.cloud.mall.admin.mapper.UserBalanceMapper;
import com.shop.cloud.mall.admin.service.UserBalanceService;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 用户余额
 *
 * @author 
 * @date 2023-11-01 09:47:36
 */
@Service
public class UserBalanceServiceImpl extends ServiceImpl<UserBalanceMapper, UserBalance> implements UserBalanceService {

    @Override
    @Klock(name = "UserBalance",keys = {"#userId"}, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    public void updateTotalAmount(String userId, BigDecimal amount) {
        if(amount.compareTo(BigDecimal.ZERO) < 0){
            //减余额则校验余额合法性
            UserBalance userBalance = baseMapper.selectById(userId);
            if(userBalance.getTotalAmount().add(amount).compareTo(BigDecimal.ZERO) < 0){
                throw new RuntimeException("非法用户余额消费");
            }
        }

        baseMapper.update(new UserBalance(), Wrappers.<UserBalance>lambdaUpdate()
                .eq(UserBalance::getUserId, userId)
                .setSql(" total_amount = total_amount + " + amount));
    }
}
